/*
*  微信小程序socket封装
*/
const wxSocket = {
  heartbeatTimerId: null,
  userInfo: null,
  options: null,
  isConnected: false,
  /**
   * options: {
   *   user_token //机智云登录凭证
   *    did //设备did
   *    app_id //机智云应用id
   * }
   *
   * */
  init(options) {
    if (!options.user_token || !options.did) {
      console.warn("参数不全, 参数:", options);
      return false;
    }
    this.options = options;
    wx.request({
      url: "https://api.gizwits.com/app/users",
      header: {
        "X-Gizwits-User-token": options.user_token,
        "X-Gizwits-Application-Id": options.app_id
      },
      success: result => {
        console.info("获取用户信息成功, 结果:", result.data);
        this.userInfo = result.data;
        console.info("开始获取设备信息");
        wx.request({
          url: `https://api.gizwits.com/app/devices/${options.did}`,
          header: {
            "X-Gizwits-User-token": options.user_token,
            "X-Gizwits-Application-Id": options.app_id
          },
          success: result => {
            console.info("获取设备数据成功, 结果:", result.data);
            if (!result.data.is_online) {
              console.warn("设备还未上线");
              options.fail && options.onFail({ code: 504, message: "设备还未上线" });
              return false;
            }
            this.initSocket(result.data);
          },
          fail: result => {
            console.warn("获取设备数据失败, 结果:", result);
          }
        });
      },
      fail: result => {
        console.warn("获取用户信息失败, 结果:", result.data);
      }
    });
  },
  sendMessage(cmd, data) {
    console.log(`下发命令:${cmd}, 参数:${JSON.stringify(data || {})}`)
    wx.sendSocketMessage({
      data: JSON.stringify({
        cmd: cmd,
        data: data || {}
      })
    });
  },
  login() {
    this.sendMessage('login_req', {
      appid: this.options.app_id,
      uid: this.userInfo.uid,
      token: this.options.user_token,
      p0_type: "attrs_v4",
      heartbeat_interval: 180,
      auto_subscribe: false
    });
  },
  startPing() {
    this.heartbeatTimerId = setInterval(() => {
      this.sendMessage("ping");
    }, 30000);
  },
  initSocket(device) {
    if(this.isConnected){
      console.info(`已存在socket连接，关闭socket...`);
      wx.closeSocket();
    }
    console.info(`开始连接socket,地址: wss://wx${device.host}/ws/app/v1`);
    wx.connectSocket({
      url: `wss://wx${device.host}/ws/app/v1`
    });
    wx.onSocketOpen(result => {
      console.log("socket连接成功");
      this.isConnected = true;
      this.login();
      this.options.onOpen && this.options.onOpen(result);
    });
    wx.onSocketError(result => {
      console.log("socket连接失败", result);
      this.options.onError && this.options.onError(result);
    });
    wx.onSocketClose(result => {
      console.log("socket关闭", result);
      this.options.onClose && this.options.onClose(result);
      this.heartbeatTimerId && clearInterval(this.heartbeatTimerId);
    });
    wx.onSocketMessage(message => {
      const result = JSON.parse(message.data);
      switch (result.cmd) {
      case "pong":
        break;
      case "login_res":
        if (result.data.success) {
          console.log("登录成功...");
          this.startPing();
          this.sendMessage('subscribe_req', [{did: device.did}])
        } else {
          console.log("登录失败，重新登录...");
          this.login();
        }
        break;
      default:
        this.options.onMessage && this.options.onMessage(result);
      }
    });
  }
};
export default wxSocket;
